package com.lg.online_shop.controller;

import com.lg.online_shop.entity.User;
import com.lg.online_shop.mapper.UserMapper;
import com.lg.online_shop.utils.JwtUtil;
import com.lg.online_shop.utils.MailService;
import com.lg.online_shop.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MailService mailService;



    // 使用内存存储验证码
    private static final Map<String, String> verificationCodes = new ConcurrentHashMap<>();

    /**
     * 生成并发送验证码到邮箱
     *
     * @param email 用户邮箱
     * @return 结果
     */
    @GetMapping("/getVerificationCode")
    public Result getVerificationCode(@RequestParam String email) {
        if (email == null || email.isEmpty()) {
            return Result.error("邮箱为空");
        }

        // 生成一个随机的4位数验证码
        String verificationCode = String.format("%06d", new Random().nextInt(9999));

        // 发送验证码到用户邮箱
        mailService.sendSimpleMail(email, "验证码", "您的验证码是：" + verificationCode);

        // 将验证码存储起来，以邮箱为键
        verificationCodes.put(email, verificationCode);

        return Result.success("验证码已发送");
    }

    /**
     * 用户注册，并校验验证码
     *
     * @param user 用户信息
     * @param verificationCode 验证码
     * @return 结果
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user, @RequestParam String verificationCode) {
        String email = user.getEmail();
        String password = user.getPassword();

        if (email == null || password == null || email.isEmpty() || password.isEmpty()) {
            return Result.error("邮箱或密码为空");
        }

        // 校验验证码
        String storedCode = verificationCodes.get(email);
        if (storedCode == null || !storedCode.equals(verificationCode)) {
            return Result.error("验证码不正确或已过期");
        }

        // 验证成功后清除验证码
        verificationCodes.remove(email);

        User u = userMapper.selectByEmail(email);
        if (u == null) {
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            int result = userMapper.insertNewUser(email, md5Password);
            return result > 0 ? Result.success("注册成功") : Result.error("注册失败");
        } else {
            return Result.error("邮箱已被使用");
        }
    }


    //    用户登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String email = user.getEmail();
        String password = user.getPassword();

        if (email == null || password == null || email.isEmpty() || password.isEmpty()) {
            return Result.error("邮箱或密码为空");
        }

        User u = userMapper.selectByEmail(email);

        if (u == null) {
            return Result.error("用户不存在");
        } else {
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            if (md5Password.equals(u.getPassword())) {
//               // 登录成功
                Map<String, Object> claims = new HashMap<>();
                claims.put("email", email);
                claims.put("nickname", u.getNickname());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            } else {
                return Result.error("密码错误");
            }
        }
    }

//    获取用户信息
    @GetMapping("/info")
    public Result getUserInfo(@RequestParam String email) {
        User user = userMapper.selectByEmail(email);
        return Result.success(user);
    }


//    用户收藏商品
    @PostMapping("/collect")
    public Result collectGood(@RequestParam Long goodId, @RequestParam Long userId) {
//        查询是否已存在
        int exist = userMapper.existCollect(goodId, userId);
        if (exist > 0) {
//          取消收藏
            return userMapper.cancelCollect(goodId, userId) > 0 ? Result.success("取消收藏") : Result.error("取消收藏失败");
        }
        int result = userMapper.collectGood(goodId, userId);
        return result > 0 ? Result.success("收藏成功") : Result.error("收藏失败");
    }


//    修改用户信息
    @PostMapping("/update")
    public Result updateUser(@RequestParam String nickName,@RequestParam String phone,@RequestParam Long userId) {
        int result =  userMapper.updateUser(nickName,phone, userId);
        return result > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }


    /**
     * 生成并发送验证码到邮箱，用于修改密码
     *
     * @param email 用户邮箱
     * @return 结果
     */
    @GetMapping("/sendResetPasswordCode")
    public Result sendResetPasswordCode(@RequestParam String email) {
        if (email == null || email.isEmpty()) {
            return Result.error("邮箱为空");
        }

        // 生成一个随机的4位数验证码
        String verificationCode = String.format("%06d", new Random().nextInt(9999));

        // 发送验证码到用户邮箱
        mailService.sendSimpleMail(email, "修改密码验证码", "您的验证码是：" + verificationCode);

        // 将验证码存储起来，以邮箱为键
        verificationCodes.put(email, verificationCode);

        return Result.success("验证码已发送");
    }

    /**
     * 修改密码
     *
     * @param email 用户邮箱
     * @param newPassword 新密码
     * @param verificationCode 验证码
     * @return 结果
     */
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestParam String email, @RequestParam String newPassword, @RequestParam String verificationCode) {
        if (email == null || email.isEmpty() || newPassword == null || newPassword.isEmpty()) {
            return Result.error("新密码为空");
        }

        // 校验验证码
        String storedCode = verificationCodes.get(email);
        if (storedCode == null || !storedCode.equals(verificationCode)) {
            return Result.error("验证码有误");
        }

        // 验证成功后清除验证码
        verificationCodes.remove(email);

        // 查询用户是否存在
        User user = userMapper.selectByEmail(email);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 更新密码
        String md5Password = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        int result = userMapper.updatePasswordByEmail(email, md5Password);

        return result > 0 ? Result.success("密码修改成功") : Result.error("密码修改失败");
    }
}
